from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, relationship

from sqlalchemy import Integer, String, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column

from typing import List

class Base(DeclarativeBase):
  pass

db = SQLAlchemy(model_class=Base)


class UserToRole(db.Model):
    __tablename__ = "user_to_role"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
    role_id: Mapped[int] = mapped_column(ForeignKey("role.id"))

class User(db.Model):
    __tablename__ = "user"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
    roles: Mapped[List["Role"]] = relationship(secondary=UserToRole.__tablename__, back_populates="users")

class Role(db.Model):
    __tablename__ = "role"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
    users: Mapped[List["User"]] = relationship(secondary=UserToRole.__tablename__, back_populates="roles")

# with app.app_context():
    # db.create_all()